<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cesium App</title>
    <script src="./Cesium/Cesium.js"></script>
    <link rel="stylesheet" href="./Cesium/Widgets/widgets.css" />
    <style>
        @import url(../templates/bucket.css);

        #toolbar {
            background: rgba(42, 42, 42, 0.8);
            padding: 4px;
            border-radius: 4px;
        }

        #toolbar input {
            vertical-align: middle;
            padding-top: 2px;
            padding-bottom: 2px;
        }

        #toolbar table tr {
            transform: translateY(0);
            transition: transform 0.4s ease-out;
        }

        #toolbar table tr.up {
            transform: translateY(33px);
            transition: none;
        }

        #toolbar table tr.down {
            transform: translateY(-33px);
            transition: none;
        }
    </style>
    <div id="cesiumContainer" class="fullSize"></div>
    <div id="loadingOverlay">
        <h1>Loading...</h1>
    </div>
    <div id="toolbar">
        <table>
            <tbody data-bind="foreach: layers">
                <tr data-bind="css: { up: $parent.upLayer === $data, down: $parent.downLayer === $data }">
                    <td><input type="checkbox" data-bind="checked: show"></td>
                    <td>
                        <span data-bind="text: name, visible: !$parent.isSelectableLayer($data)"></span>
                        <select
                            data-bind="visible: $parent.isSelectableLayer($data), options: $parent.baseLayers, optionsText: 'name', value: $parent.selectedLayer"></select>
                    </td>
                    <td>
                        <input type="range" min="0" max="1" step="0.01" data-bind="value: alpha, valueUpdate: 'input'">
                    </td>
                    <td>
                        <button type="button" class="cesium-button"
                            data-bind="click: function() { $parent.raise($data, $index()); }, visible: $parent.canRaise($index())">
                            ▲
                        </button>
                    </td>
                    <td>
                        <button type="button" class="cesium-button"
                            data-bind="click: function() { $parent.lower($data, $index()); }, visible: $parent.canLower($index())">
                            ▼
                        </button>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
</head>

<body>
    <script>
        const viewer = new Cesium.Viewer("cesiumContainer", {
            baseLayerPicker: false,
            animation: false,
            fullscreenButton: false,
            vrButton: false,
            homeButton: false,
            sceneModePicker: false,
            timeline: false,
            navigationHelpButton: false,
            geocoder: false, //是否显示地名查找控件 
        });
        //去掉logo
        viewer.cesiumWidget.creditContainer.style.display = "none"

        const imageryLayers = viewer.imageryLayers;
        const viewModel = {
            layers: [],
            baseLayers: [],
            upLayer: null,
            downLayer: null,
            selectedLayer: null,
            isSelectableLayer: function (layer) {
                return this.baseLayers.indexOf(layer) >= 0;
            },
            // 图层上升
            raise: function (layer, index) {
                console.log(viewModel.layers, 0)
                imageryLayers.raise(layer);
                // 上升图层对象
                viewModel.upLayer = layer;
                // 下降图层对象
                viewModel.downLayer = viewModel.layers[Math.max(0, index - 1)];
                updateLayerList();
                window.setTimeout(function () {
                    viewModel.upLayer = viewModel.downLayer = null;
                }, 10);
            },
            // 图层下降
            lower: function (layer, index) {
                imageryLayers.lower(layer);
                viewModel.upLayer =
                    viewModel.layers[
                    Math.min(viewModel.layers.length - 1, index + 1)
                    ];
                viewModel.downLayer = layer;
                updateLayerList();
                window.setTimeout(function () {
                    viewModel.upLayer = viewModel.downLayer = null;
                }, 10);
            },
            // 是否可以提升
            canRaise: function (layerIndex) {
                return layerIndex > 0;
            },
            // 是否可以下降
            canLower: function (layerIndex) {
                return layerIndex >= 0 && layerIndex < imageryLayers.length - 1;
            },
        };
        const baseLayers = viewModel.baseLayers;

        // 这个操作是向你的Cesium中添加一个自定义的html控制面板，从而通过改变控制面板中参数的状态，来动态改变Cesium中的相关参数
        Cesium.knockout.track(viewModel);

        function setupLayers() {
            // 添加基础层选项
            addBaseLayerOption("Bing Maps Aerial", undefined); // 当前的基础层
            addBaseLayerOption(
                "必应地图路",
                Cesium.createWorldImagery({
                    style: Cesium.IonWorldImageryStyle.ROAD,
                })
            );
            addBaseLayerOption(
                "ArcGIS世界街道地图",
                new Cesium.ArcGisMapServerImageryProvider({
                    url:
                        "https://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer",
                })
            );
            addBaseLayerOption(
                "公开街道地图",
                new Cesium.OpenStreetMapImageryProvider()
            );
            // addBaseLayerOption(
            //     "Stamen Maps",
            //     new Cesium.OpenStreetMapImageryProvider({
            //         url: "https://stamen-tiles.a.ssl.fastly.net/watercolor/",
            //         fileExtension: "jpg",
            //         credit:
            //             "Map tiles by Stamen Design, under CC BY 3.0. Data by OpenStreetMap, under CC BY SA.",
            //     })
            // );
            // addBaseLayerOption(
            //     "Natural Earth II (local)",
            //     new Cesium.TileMapServiceImageryProvider({
            //         url: Cesium.buildModuleUrl("Assets/Textures/NaturalEarthII"),
            //     })
            // );
            // addBaseLayerOption(
            //     "USGS Shaded Relief (via WMTS)",
            //     new Cesium.WebMapTileServiceImageryProvider({
            //         url:
            //             "https://basemap.nationalmap.gov/arcgis/rest/services/USGSShadedReliefOnly/MapServer/WMTS",
            //         layer: "USGSShadedReliefOnly",
            //         style: "default",
            //         format: "image/jpeg",
            //         tileMatrixSetID: "default028mm",
            //         maximumLevel: 19,
            //         credit: "U. S. Geological Survey",
            //     })
            // );

            // 创建额外的图层
            addAdditionalLayerOption(
                "测试",
                new Cesium.WebMapServiceImageryProvider({
                    url:
                        "https://mesonet.agron.iastate.edu/cgi-bin/wms/goes/conus_ir.cgi?",
                    layers: "goes_conus_ir",
                    credit: "Infrared data courtesy Iowa Environmental Mesonet",
                    parameters: {
                        transparent: "true",
                        format: "image/png",
                    },
                })
            );
            addAdditionalLayerOption(
                "United States Weather Radar",
                new Cesium.WebMapServiceImageryProvider({
                    url:
                        "https://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r.cgi?",
                    layers: "nexrad-n0r",
                    credit: "Radar data courtesy Iowa Environmental Mesonet",
                    parameters: {
                        transparent: "true",
                        format: "image/png",
                    },
                })
            );
            addAdditionalLayerOption(
                "TileMapService Image",
                new Cesium.TileMapServiceImageryProvider({
                    url: "./img/wx.png",
                }),
                0.2
            );
            // addAdditionalLayerOption(
            //     "Single Image",
            //     new Cesium.SingleTileImageryProvider({
            //         url: "../images/Cesium_Logo_overlay.png",
            //         rectangle: Cesium.Rectangle.fromDegrees(
            //             -115.0,
            //             38.0,
            //             -107,
            //             39.75
            //         ),
            //     }),
            //     1.0
            // );
            // addAdditionalLayerOption(
            //     "Grid",
            //     new Cesium.GridImageryProvider(),
            //     1.0,
            //     false
            // );
            // addAdditionalLayerOption(
            //     "Tile Coordinates",
            //     new Cesium.TileCoordinatesImageryProvider(),
            //     1.0,
            //     false
            // );
        }

        // 添加基础层
        function addBaseLayerOption(name, imageryProvider) {
            let layer;
            if (typeof imageryProvider === "undefined") {
                layer = imageryLayers.get(0);
                viewModel.selectedLayer = layer;
            } else {
                layer = new Cesium.ImageryLayer(imageryProvider);
            }

            layer.name = name;
            baseLayers.push(layer);
        }

        // 创建额外的图层及修改图层属性
        function addAdditionalLayerOption(name, imageryProvider, alpha, show) {
            const layer = imageryLayers.addImageryProvider(imageryProvider);
            // const layer = viewer.imageryLayers.addImageryProvider(
            //     new Cesium.IonImageryProvider({ assetId: 3812 })
            // );
            layer.alpha = Cesium.defaultValue(alpha, 0.7);
            layer.show = Cesium.defaultValue(show, true);
            layer.name = name;
            Cesium.knockout.track(layer, ["alpha", "show", "name"]);
        }

        // 图层排序，更新viewModel中图层数据
        function updateLayerList() {
            const numLayers = imageryLayers.length;
            viewModel.layers.splice(0, viewModel.layers.length); // 清空layers
            for (let i = numLayers - 1; i >= 0; --i) {
                console.log(imageryLayers.get(i),i)
                viewModel.layers.push(imageryLayers.get(i));
            }
        }

        setupLayers();
        updateLayerList();


        // 将viewModel绑定到调用它的UI的DOM元素
        const toolbar = document.getElementById("toolbar");
        Cesium.knockout.applyBindings(viewModel, toolbar);

        // 处理对下拉基础层选择器的更改.
        Cesium.knockout.getObservable(viewModel, "selectedLayer").subscribe(function (baseLayer) {
            console.log(baseLayer,'baseLayer')
            // 活跃的图层
            let activeLayerIndex = 0;
            // 图层数量
            const numLayers = viewModel.layers.length;

            for (let i = 0; i < numLayers; ++i) {
                if (viewModel.isSelectableLayer(viewModel.layers[i])) {
                    activeLayerIndex = i;
                    break;
                }
            }
            const activeLayer = viewModel.layers[activeLayerIndex];
            const show = activeLayer.show;
            const alpha = activeLayer.alpha;
            imageryLayers.remove(activeLayer, false);
            imageryLayers.add(baseLayer, numLayers - activeLayerIndex - 1);
            baseLayer.show = show;
            baseLayer.alpha = alpha;
            updateLayerList();
        });
    </script>
</body>>

</html>>